import { createRouter, createWebHistory } from 'vue-router';
import { useAuthStore } from '@/stores/auth'; // 引入 Pinia store

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            redirect: '/login', // 默认重定向到登录页面
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('@/views/Login.vue'),
            meta: { guestOnly: true }, // 仅游客可以访问
        },
        {
            path: '/register',
            name: 'register',
            component: () => import('@/views/Register.vue'),
            meta: { guestOnly: true },
        },
        {
            path: '/layout',
            name: 'layout',
            component: () => import('@/components/Layout.vue'),
            children: [
                {
                    path: '/',
                    redirect: '/home',
                },
                {
                    path: '/home',
                    name: 'home',
                    component: () => import('@/views/Home.vue'),
                    meta: { requiresAuth: true }, // 需要登录才能访问
                },
                {
                    path: '/books',
                    name: 'books',
                    component: () => import('@/views/BookManage.vue'),
                    meta: { requiresAuth: true },
                },
                {
                    path:'/about',
                    name: 'about',
                    component: () => import('@/views/About.vue'),
                    meta: { requiresAuth: true },
                }
            ],
        },
    ],
});

// 路由守卫
router.beforeEach((to, from, next) => {
    const authStore = useAuthStore();
    const isAuthenticated = authStore.isAuthenticated;

    // 如果访问的路由需要认证，但用户未登录
    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login'); // 重定向到登录页
    } else if (to.meta.guestOnly && isAuthenticated) {
        next('/home'); // 如果用户已登录并访问了登录或注册页面，跳转到首页
    } else {
        next(); // 允许访问目标页面
    }
});

export default router;
